<template>
  <el-card style="margin-top:10px">
    <el-form inline>
      <el-form-item>
        <el-input v-model="searchObj.username" />
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      <el-button @click="searchObj.username=''">清空</el-button>
    </el-form>

    <div style="margin-bottom:20px">
      <el-button v-show="$store.state.user.buttons.indexOf('btn.User.add')!==-1" type="primary" @click="show(1)">添加</el-button>
      <el-button v-show="$store.state.user.buttons.indexOf('btn.User.remove')!==-1" type="danger" :disabled="selectedIds.length===0" @click="delmore">批量删除</el-button>
    </div>

    <el-table
      style="width: 100%"
      :data="data"
      border
      @selection-change="changeSel"
    >
      <template slot="empty">
        <el-empty description="空" />
      </template>
      <el-table-column
        prop="prop"
        width="55"
        type="selection"
      />
      <el-table-column
        prop="prop"
        label="序号"
        width="80"
        type="index"
      />
      <el-table-column
        prop="username"
        label="用户名"
        width="150"
      />
      <el-table-column
        prop="nickName"
        label="用户昵称"
        width="width"
      />
      <el-table-column
        prop="roleName"
        label="权限列表"
        width="width"
      />
      <el-table-column
        prop="gmtCreate"
        label="创建时间"
        width="180"
      />
      <el-table-column
        prop="gmtModified"
        label="更新时间"
        width="180"
      />
      <el-table-column
        prop="prop"
        label="操作"
        width="width"
      >
        <template slot-scope="{row}">
          <div>
            <el-button
              type="info"
              :disabled="$store.state.user.buttons.indexOf('btn.User.assgin')===-1"
              title="分配角色"
              icon="el-icon-user-solid"
              size="mini"
              @click="assignRolesFn(row)"
            />
            <el-button
              type="primary"
              :disabled="$store.state.user.buttons.indexOf('btn.User.update')===-1"
              title="修改用户"
              icon="el-icon-edit"
              size="mini"
              style="margin-right:10px"
              @click="show(row)"
            />
            <el-popconfirm
              :title="`确定删除${row.username}吗?`"
              @confirm="del(row)"
            >
              <el-button
                slot="reference"
                type="danger"
                :disabled="$store.state.user.buttons.indexOf('btn.User.remove')===-1"
                title="删除用户"
                icon="el-icon-delete"
                size="mini"
              />
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加用户 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="dialogVisible"
    >
      <el-form ref="ruleForm" :model="user" :rules="rules">
        <el-form-item label="用户名" prop="username" required label-width="100px">
          <el-input v-model.trim="user.username" :disabled="title==='设置角色'" />
        </el-form-item>
        <el-form-item v-if="title!=='设置角色'" label="用户昵称" label-width="100px">
          <el-input v-model.trim="user.nickName" />
        </el-form-item>
        <el-form-item v-if="title==='设置角色'" label="角色列表" label-width="100px">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="assignRoles">
            <el-checkbox v-for="item in allRolesList" :key="item.id" :label="item.id">{{ item.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="title==='添加用户'" prop="password" label="用户密码" required label-width="100px">
          <el-input v-model.trim="user.password" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="checkAdd">确 定</el-button>
      </div>
    </el-dialog>

    <el-pagination
      :page-size="5"
      :page-sizes="[5,10,15]"
      :current-page="page"
      layout="prev,pager,next,jumper,->,sizes,total"
      :total="total"
      @current-change="change"
      @size-change="sizeChange"
    />
  </el-card>
</template>

<script>
// 引入lodash中的深拷贝
import { cloneDeep } from 'lodash'
export default {
  data() {
    return {
      searchObj: {
        username: ''
      },
      page: 1,
      limit: 5,
      total: 0,
      data: [],
      dialogVisible: false,
      selectedIds: [],
      // 新增用户
      user: {
        username: '',
        nickName: '',
        password: ''
      },
      title: '',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ]
      },
      checkAll: false,
      assignRoles: [],
      allRolesList: [],
      isIndeterminate: true
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await this.$api.user.getPageList(this.page, this.limit, this.searchObj)
      if (res.code === 20000) {
        this.data = res.data.items
        this.total = res.data.total
      }
    },
    change(e) {
      this.page = e
      this.getData()
    },
    sizeChange(e) {
      this.limit = e
      this.getData()
    },
    changeSel(e) {
      this.selectedIds = []
      e.map(item => {
        this.selectedIds.push(item.id)
      })
    },
    search() {
      this.page = 1
      this.limit = 5
      this.getData()
    },
    show(e) {
      if (e === 1) {
        this.title = '添加用户'
      } else {
        this.user = cloneDeep(e)
        this.title = '修改用户'
      }
      this.dialogVisible = true
    },
    // 分配角色
    async assignRolesFn(e) {
      this.title = '设置角色'
      this.user = cloneDeep(e)
      // 获取当前用户的角色
      const res = await this.$api.user.getRoles(e.id)
      if (res.code === 20000) {
        this.allRolesList = res.data.allRolesList
        this.assignRoles = []
        res.data.assignRoles.map(item => {
          this.assignRoles.push(item.id)
        })
      }
      this.dialogVisible = true
    },
    handleCheckAllChange(val) {
      this.assignRoles = []
      if (val) {
        this.allRolesList.map(item => {
          this.assignRoles.push(item.id)
        })
      }
      this.isIndeterminate = false
    },
    // 删除用户
    async del(e) {
      const res = await this.$api.user.removeById(e.id)
      if (res.code === 20000) {
        this.$message({ type: 'success', message: '删除成功' })
        this.getData()
      }
    },
    async delmore() {
      for (let i = 0; i < this.selectedIds.length; i++) {
        const res = await this.$api.user.removeById(this.selectedIds[i])
        if (res.code !== 20000) {
          this.$message.error('删除失败')
        }
      }
      this.getData()
    },
    // 确认添加
    checkAdd() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          for (var propName in this.user) {
            if (this.user[propName] === '') {
              delete this.user[propName]
            }
          }
          if (this.title === '添加用户') {
            const res = await this.$api.user.add(this.user)
            if (res.code === 20000) {
              this.$message({ type: 'success', message: '添加成功' })
              this.getData()
              this.$refs.ruleForm.resetFields()
              this.dialogVisible = false
            }
          } else if (this.title === '修改用户') {
            const res = await this.$api.user.update(this.user)
            if (res.code === 20000) {
              this.$message({ type: 'success', message: '添加成功' })
              this.getData()
              this.$refs.ruleForm.resetFields()
              this.dialogVisible = false
            }
          } else {
            const res = await this.$api.user.assignRoles(this.user.id, this.assignRoles.join())
            if (res.code === 20000) {
              this.$message({ type: 'success', message: '修改成功' })
              this.getData()
              this.dialogVisible = false
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    close() {
      this.user = {
        username: '',
        nickName: '',
        password: ''
      }
      this.$refs.ruleForm.resetFields()
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>

</style>

